package jdbc;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

/**
 * 帮助开发者进行数据库的增删改查操作
 */
public class BaseDao<T> {

    //2. QueryRunner对象
    private QueryRunner runner=new QueryRunner();
    /**
     * 对数据库进行增删改的操作
     */
    public boolean update(String sql,Object...params){
        //1. 获得数据库连接
        Connection connection= JDBCUtil.getConnection();
        //3. 执行
        try {
            int update = runner.update(connection, sql, params);
            if(update>0)
                return true;
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            JDBCUtil.closeConnection(connection,null,null);
        }
        return false;
    }

    /**
     * 查询一条
     * @param type 用来接数据库返回值的对象的运行时类型
     * @param sql
     * @param params
     * @return
     */
    public T getBean(Class type,String sql,Object...params){
        //1. 获得数据库连接
        Connection connection= JDBCUtil.getConnection();
        try {
            return  runner.query(connection, sql, new BeanHandler<T>(type), params);
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            JDBCUtil.closeConnection(connection,null,null);
        }
        return null;
    }

    /**
     * 查询多条
     * @param type 用来接数据库返回值的对象的运行时类型
     * @param sql
     * @param params
     * @return
     */
    public List<T> getBeanList(Class type,String sql,Object...params){
        Connection connection=JDBCUtil.getConnection();
        try {
            List<T> query = runner.query(connection, sql, new BeanListHandler<T>(type), params);
            return query;
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            JDBCUtil.closeConnection(connection,null,null);
        }
        return null;
    }

    /**
     * 查询一个数据,如count(1)
     * @param sql
     * @param params
     * @return
     */
    public Object getOnly(String sql,Object...params){
        Connection connection=JDBCUtil.getConnection();
        try {
            return runner.query(connection,sql,new ScalarHandler<Object>(),params);
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            JDBCUtil.closeConnection(connection,null,null);
        }
        return null;
    }
}
